<template>
  <div class="app-container">
    <el-form :inline="true" :model="recordInfo.queryForm" class="demo-form-inline">

      <el-form-item label="明细编号">
        <el-input v-model="recordInfo.queryForm.memberCardChangeRecordId" placeholder="明细编号" clearable
          style="width: 220px;" />
      </el-form-item>

      <el-form-item label="订单编号">
        <el-input v-model="recordInfo.queryForm.orderNo" placeholder="订单编号" clearable style="width: 220px;" />
      </el-form-item>

      <el-form-item label="会员手机">
        <el-input v-model="recordInfo.queryForm.mobile" @clear="clearMobile" placeholder="手机号" :maxlength="11"
          @input="handleMobileInput" clearable />
      </el-form-item>

      <!-- <el-form-item label="门店名称/机构编号">
        <el-input v-model="recordInfo.queryForm.storeKeyword" placeholder="门店名称/机构编号" clearable style="width: 220px;" />
      </el-form-item> -->

      <el-form-item label="明细类型">
        <el-select v-model="recordInfo.queryForm.detailType" clearable placeholder="明细类型" style="width: 220px">
          <el-option v-for="item in detailTypeList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <OrganizationSelector
        v-model="organizationQuery"
        :user-type="userInfo.organizationType"
      />

      <!-- <el-form-item label="所属总部" v-if="headquartersList.length > 0">
        <el-select v-model="recordInfo.queryForm.headquartersId" clearable placeholder="所属总部" style="width: 220px">
          <el-option v-for="item in headquartersList" :key="item.value" :label="item.organizationName"
            :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="所属连锁" v-if="userInfo.organizationType == 4">
        <el-select v-model="recordInfo.queryForm.chainId" clearable placeholder="所属连锁" style="width: 220px"
          @change="onChainChange">
          <el-option v-for="item in chainList" :key="item.chainOrganizationId" :label="item.organizationName"
            :value="item.chainOrganizationId" />
        </el-select>
      </el-form-item>

      <el-form-item label="所属门店">
        <el-select v-model="recordInfo.queryForm.storeId" clearable placeholder="所属门店" style="width: 220px">
          <el-option v-for="item in storeList" :key="item.organizationId" :label="item.organizationName"
            :value="item.organizationId" />
        </el-select>
      </el-form-item> -->

      <el-form-item label="创建时间">
        <el-date-picker v-model="createTimeValue" type="daterange" :picker-options="pickerOptions" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" :default-time="defaultTime"
          @change="dateChange('createTimeValue')" style="width: 300px" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <div style="display: flex;justify-content: space-between;align-items: center; margin-bottom: 10px;">
      <h5 style="margin: 0; font-size: 16px;">流水列表</h5>
    </div>

    <el-table v-loading="recordInfo.loading" class="table-default" :data="recordInfo.list" border style="width: 100%"
      max-height="600">
      <el-table-column type="index" label="序号" width="60" align="center" />

      <el-table-column prop="memberCardChangeRecordId" label="明细编号" width="200" align="center" />

      <el-table-column prop="orderNo" label="订单编号" width="200" align="center" />

      <el-table-column label="会员信息" width="230" align="center">
        <template slot-scope="scope">
          <div class="member-info-cell">
          <image-show :md5="scope.row.photoDownloadCode || ''" style="width:40px;height:40px;margin-right: 10px;" />
            <div class="member-text">
              <p class="name">{{ scope.row.userName }}</p>
              <p class="id-phone">ID: {{ scope.row.userId }}</p>
              <p class="id-phone">{{ scope.row.mobile }}</p>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="detailTypeName" label="明细类型" width="140" align="center" />
      <el-table-column prop="amount" label="金额" width="120" align="center" />
      <el-table-column prop="paymentAmount" label="金额组成" width="110" align="center">
        <template slot-scope="scope">
          <div style="white-space: pre-line;">{{ `实充${scope.row.paymentAmount}` }}</div>
          <div style="white-space: pre-line;">{{ `赠送¥${scope.row.giftAmount}` }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="140" align="center" />
      <el-table-column prop="headquartersName" label="所属总部" align="center" />
      <el-table-column prop="chainName" label="所属连锁" align="center"/>
      <el-table-column prop="organizationName" label="所属门店" align="center" />

    </el-table>

    <pagination v-show="recordInfo.total > 0" :total="recordInfo.total" :page.sync="recordInfo.queryForm.page"
      :limit.sync="recordInfo.queryForm.pageSize" @pagination="getRecordList" :page-sizes="[10, 20, 50, 100]">
    </pagination>
  </div>
</template>

<script>
import OrganizationSelector from '@/views/member/components/OrganizationSelector.vue'
import { mapGetters } from 'vuex'
import filters from '@/filters/index'
import ListMixin from '@/mixins/modules/list'
import messageMixin from '@/mixins/modules/message'
import Pagination from '@/components/Pagination'
import imageShow from '@/components/imageShow'

export default {
  components: {
    Pagination,
    imageShow,
    OrganizationSelector
  },
  filters: { ...filters },
  mixins: [ListMixin, messageMixin],
  data() {
    return {
      createTimeValue: null,
      recordInfo: {
        queryForm: {
          page: 1,
          pageSize: 10,
          mobile: '',
          returnCount: true,
          userId: '',
          orderBy: 'createTimeDesc',
          // 查询表单字段
          memberCardChangeRecordId: '',
          orderNo: '',
          memberKeyword: '',
          storeKeyword: '',
          detailType: '',
          headquartersId: '',
          chainId: '',
          storeId: '',
        },
        requestUrl: this.$api.getCardRecord, // 假设存在流水列表接口
        list: [],
        total: 0,
        loading: false
      },
      // 1: 充值获得, 2: 消费支付扣除, 3: 消费退款返还 4:充值退款返还
      detailTypeList: [
        { name: '充值获得', value: 1 },
        { name: '消费支付扣除', value: 2 },
        { name: '消费退款返还', value: 3 },
        { name: '充值退款返还', value: 4 }
      ],
      headquartersList: [],
      chainList: [],
      storeList: [],

      // **关键配置**：告知 Mixin 哪些字段需要进行日期转换
      changeDateNameInfo: {
        createTimeValue: ['detailStartTime', 'detailEndTime']
      },
      getListCallback: (res) => {
        if (res.list && res.list.length > 0) {
          res.list.forEach(item => {
            // 1. 格式化时间
            item.createTime = this.$commonUtils.getShowTime(item.createTime)

            // 2. 明细类型映射
            const typeItem = this.detailTypeList.find(t => t.value === item.detailType)
            item.detailTypeName = typeItem ? typeItem.name : '未知'
            item.usageCount = item.usageCount + '次' // 格式化使用次数

            // 3. 格式化金额，并添加正负号（设计稿中有 +200.00, -200.00）
            item.amount = ' ¥' + this.$amountUtils.getYuan(item.amount)
            item.paymentAmount = ' ¥' + this.$amountUtils.getYuan(item.paymentAmount)
            item.giftAmount = ' ¥' + this.$amountUtils.getYuan(item.giftAmount)
            // 4. 模拟会员信息
            if (!item.memberAvatar) {
              item.memberAvatar = '/static/default-avatar.png'
            }
          })
        }
        // 更新列表和总数
        this.recordInfo.list = res.list || []
      },
      beforeRequest: () => {
        this.changeDate(this.createTimeValue, 'createTimeValue')
        this.recordInfo.queryForm.returnCount = this.recordInfo.queryForm.page === 1
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    organizationQuery: {
      get() {
        return {
          headquartersId: this.recordInfo.queryForm.headquartersId,
          chainId: this.recordInfo.queryForm.chainId,
          storeId: this.recordInfo.queryForm.storeId,
        };
      },
      set(newVal) {
        this.recordInfo.queryForm.headquartersId = newVal.headquartersId;
        this.recordInfo.queryForm.chainId = newVal.chainId;
        this.recordInfo.queryForm.storeId = newVal.storeId;
      }
    }
  },
  // watch: {
  //   // 监听 organizationQuery 的变化，同步到 recordInfo.queryForm
  //   organizationQuery: {
  //     handler(newVal) {
  //       this.recordInfo.queryForm.headquartersId = newVal.headquartersId;
  //       this.recordInfo.queryForm.chainId = newVal.chainId;
  //       this.recordInfo.queryForm.storeId = newVal.storeId;
  //     },
  //     deep: true
  //   }
  // },
  methods: {
    clearMobile() {
      this.recordInfo.queryForm.mobile = '';
      this.recordInfo.queryForm.userId = '';
    },
    handleMobileInput(value) {
      const mobileNumber = value.trim();
      if (mobileNumber.length === 11) {
        console.log('手机号大于七位，触发查询请求:', mobileNumber);
        this.$api.getMemberInfoList({
          returnUserDetail: true,
          returnCount: false,
          orderBy: 'createTimeDesc',
          mobile: mobileNumber,
          pageSize: 100,
          page: 1
        }).then(response => {
          console.log('查询结果:', response.list);
          if (response.list && response.list.length > 0) {
            this.recordInfo.queryForm.userId = response.list[0].userId;
          }else{
            this.recordInfo.queryForm.userId = '999999999'; // 设置一个不存在的用户ID，确保查询无结果
          }
          // 处理查询结果
        })
          .catch(error => {
            console.error('查询出错:', error);
          });
      }
    },
    // 查询按钮，利用 Mixin 的 getRecordList
    search() {
      this.recordInfo.queryForm.page = 1
      this.getRecordList()
    },

    // 重置表单，清空所有查询条件
    resetForm() {
      // 业务字段清空
      this.recordInfo.queryForm = {
        page: 1,
        pageSize: 10,
        orderBy: 'createTimeDesc',
        memberCardChangeRecordId: '',
        orderNo: '',
        memberKeyword: '',
        storeKeyword: '',
        detailType: '',
        headquartersId: '', // 清空
    chainId: '',        // 清空
    storeId: '',        // 清空
      }
      // 日期清空
      this.createTimeValue = null
      // 重新查询
      this.search()
    },

    // 查看详情
    goDetail(item) {
      this.$addTab('valueChangeLogDetail', {
        memberCardChangeRecordId: item.memberCardChangeRecordId
      }, '流水详情 - ' + item.memberCardChangeRecordId)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.demo-form-inline {
  padding-bottom: 5px;

  .el-form-item {
    margin-right: 15px;
    margin-bottom: 10px;
  }
}

/* --- 表格样式 --- */

.member-info-cell {
  display: flex;
  align-items: center;

  .avatar-sm {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 8px;
    object-fit: cover;
    border: 1px solid #eee;
  }

  .member-text {
    text-align: left;

    p {
      margin: 0;
      line-height: 1.2;
    }

    .name {
      font-weight: bold;
      color: #333;
    }

    .id-phone {
      font-size: 12px;
      color: #999;
    }
  }
}

// 使金额列右对齐
::v-deep .el-table {

  // 金额列 (第5列)
  .el-table__cell:nth-child(5) {
    .cell {
      text-align: right;
    }
  }
}

/* --- 分页底部统计样式 --- */
.pagination-summary {
  display: inline-block;
  margin-right: 20px;
  font-size: 14px;
  color: #606266;

  .value {
    color: #F07505;
    font-weight: bold;
    margin: 0 5px;
  }
}
</style>
